<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>10_ComponentLife</title>
</head>
<body>
<div id="example"></div>

<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script type="text/babel">
    /*
    需求: 自定义组件
      1. 让指定的文本做显示/隐藏的动画
      2. 切换时间为2S
      3. 点击按钮从界面中移除组件界面
     */
    class Life extends React.Component {
        constructor(props) {
            super(props);

            //初始化状态
            this.state = {
                opacity: 1
            };

            this.distoryComponent = this.distoryComponent.bind(this);
        }

        componentDidMount() {
            //启动循环计时器
            this.opacityInterval = setInterval(function () {
                console.log("定时器执行中");
                let {opacity} = this.state;
                if (opacity <= 0) {
                    opacity = 1.1;
                }
                opacity -= 0.1;
                this.setState({opacity});
            }.bind(this), 150);
        }

        componentWillUnmount() {
            //清除定时器
            clearInterval(this.opacityInterval);
        }

        distoryComponent() {
            ReactDOM.unmountComponentAtNode(document.getElementById('example'));
        }

        render() {
            const {opacity} = this.state;

            return (
                <div>
                    <h2 style={{opacity: opacity}}>{this.props.msg}</h2>
                    <button onClick={this.distoryComponent}>不学了</button>
                </div>
            )
        }
    }

    ReactDOM.render(<Life msg="react太难学了！"/>, document.getElementById('example'));
</script>
</body>
</html>
